package com.qiantu.phone.ui.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.qiantu.api.entity.DeviceBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppAdapter;
import com.qiantu.phone.glide.GlideApp;

public final class DataSourceDeviceAdapter extends AppAdapter<DeviceBean> {

    private DeviceBean selected = null;
    public DataSourceDeviceAdapter(Context context) {
        super(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    private final class ViewHolder extends AppAdapter<?>.ViewHolder {

        private final ImageView icon;
        private final TextView tvName;
        private final TextView checkView;

        private ViewHolder() {
            super(R.layout.item_data_source_device);
            icon = findViewById(R.id.icon);
            tvName = findViewById(R.id.tv_name);
            checkView = findViewById(R.id.check_view);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if(checkView.isSelected()){
                return;
            }
            checkView.setSelected(!checkView.isSelected());
            DeviceBean data = (DeviceBean) view.getTag();
            selected = data;
            notifyDataSetChanged();
            super.onClick(view);
        }

        @Override
        public void onBindView(int position) {
            DeviceBean device = getItem(position);
            tvName.setText(device.getName());
            itemView.setTag(getItem(position));
            GlideApp.with(icon).load(device.getOnImageUrl()).into(icon);
            if(selected != null && selected.equals(getItem(position))){
                checkView.setSelected(true);
            }else{
                checkView.setSelected(false);
            }
        }
    }

    public DeviceBean getSelected() {
        return selected;
    }

    public void checkSelected(DeviceBean selected){
        if(selected != null){
            this.selected = selected;
            notifyDataSetChanged();
        }
    }

    public void checkSelected(String serialNo){
        for(DeviceBean device : getData()){
            if(device.getDeviceSerialNo().equals(serialNo)){
                this.selected = device;
                notifyDataSetChanged();
                break;
            }
        }
    }
}